package myfirstgrailsproject


/**
 * This class is a data-holder - this is what
 * we store in the database.
 *
 * @author zach
 *
 */
class User implements Serializable{

	public static enum UserType {STUDENT, INSTRUCTOR, ADMIN};

	//These will be shown on the new user page
	String username;
	String password;
	String firstName;
	String lastName;
	String email;


	//These don't appear on the new user page
	int loginAttempts;
	UserType userType;
	boolean locked;


	static constraints = {
		username(unique:true, nullable:false, blank:false, matches:"[a-z]+[0-9]*", maxSize:50);
		password(nullable:false, blank:false, password:true, size:4..50);
		firstName(nullable:false, blank:false, matches:"[A-Z][a-z]+", maxSize:50);
		lastName(nullable:false, blank:false, matches:"[A-Z][a-z]+", maxSize:50);
		email(unique:true, nullable:false, blank:false, email:true);
		userType(nullable:false, blank:false, inList:[UserType.ADMIN, UserType.INSTRUCTOR, UserType.STUDENT]);
		loginAttempts(display:false, blank:true, nullable:true);
		//courses(display:true, blank:true, nullable:true);
		team(display:false, blank:true, nullable:true)
		locked(display:false, blank:true, nullable:true);
		enrollments(display:true, blank:true, nullable:true);
	}

	static hasMany = [enrollments:Enrollment];
	static belongsTo = [team:Team];

	def courses(){
		return enrollments.collect{it.course};
	}

	def getCourses(){
		return enrollments.collect{it.course};
	}

	def beforeInsert = {

		locked = false;
		loginAttempts=0;
		if (!userType){
			userType = UserType.STUDENT
		}
		password = password.encodeAsSHA();
	}

	String toString(){
		firstName + " " + lastName
	}

	static transients = ['admin', 'instructor', 'student']; //admin won't be a persisted field

	boolean isAdmin(){
		return userType == UserType.ADMIN;
	}

	boolean isInstructor(){
		return userType == UserType.INSTRUCTOR;
	}

	boolean isStudent(){
		return userType == UserType.STUDENT;
	}
}
